# -*- encoding: utf-8 -*-

"""
@File:      tc_libfastjson_libfastjson_func_001.py
@Time:      2024/04/01 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libfastjson_libfastjson_func_001.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "libfastjson libfastjson-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >fjson_test1.c<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <libfastjson/json.h>

int main() {
    // 创建包含所有JSON数据类型的示例JSON字符串
    const char *json_string = "{\\"object\\": {\\"key\\": \\"value\\"}, \\"array\\": [1, 2, 3], \\"string\\": \\"hello\\", \\"number\\": 123, \\"boolean\\": true, \\"null\\": null }";
    fjson_object *parsed_json;

    // 解析JSON字符串
    parsed_json = fjson_tokener_parse(json_string);
    if (!parsed_json) {
        fprintf(stderr, "解析 JSON 失败。\\n");
        return EXIT_FAILURE;
    }

    // 打印出解析后的JSON结构
    printf("解析后的JSON:\\n%s\\n", fjson_object_to_json_string_ext(parsed_json, FJSON_TO_STRING_PRETTY));

    // 获取并输出各种JSON类型
    fjson_object *object, *array, *string, *number, *boolean, *null_value;
    fjson_object_object_get_ex(parsed_json, "object", &object);
    fjson_object_object_get_ex(parsed_json, "array", &array);
    fjson_object_object_get_ex(parsed_json, "string", &string);
    fjson_object_object_get_ex(parsed_json, "number", &number);
    fjson_object_object_get_ex(parsed_json, "boolean", &boolean);
    fjson_object_object_get_ex(parsed_json, "null", &null_value);

    printf("对象类型: %s\\n", fjson_object_to_json_string(object));
    printf("数组类型: %s\\n", fjson_object_to_json_string(array));
    printf("字符串类型: %s\\n", fjson_object_to_json_string(string));
    printf("数字类型: %d\\n", fjson_object_get_int(number));
    printf("布尔类型: %s\\n", fjson_object_get_boolean(boolean) ? "true" : "false");
    printf("空值类型: %s\\n", fjson_object_to_json_string(null_value));

    // 释放JSON对象的内存
    fjson_object_put(parsed_json);

    return 0;
}
EOF'''
        self.cmd(cmdline)


    def test(self):
        self.cmd("gcc -o fjson_test1 fjson_test1.c -lfastjson")
        code, fjson_result = self.cmd("./fjson_test1")
        self.assertIn('对象类型: { "key": "value" }', fjson_result)
        self.assertIn('数组类型: [ 1, 2, 3 ]', fjson_result)
        self.assertIn('字符串类型: "hello"', fjson_result)
        self.assertIn('数字类型: 123', fjson_result)
        self.assertIn('布尔类型: true', fjson_result)
        self.assertIn('空值类型: null', fjson_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf fjson_test1.c fjson_test1")
